<template>
  <div class="page-Body">
    <h2 class="page-title">隐私政策</h2>
    <div class="privacy-container">
      <!-- 文本版本号输入框 -->
      <div class="input-section">
        <span class="label">隐私政策-版本号：</span>
        <el-input
          v-model="versionNumber"
          placeholder="请先输入版本号之后再上传文件"
          clearable
          v-noSpace
          :disabled="!!uploadedFile"
          style="width: 275px"
        />
      </div>

      <!-- 文件上传区域 -->
      <div class="upload-section">
        <el-upload
          class="upload-box"
          action="#"
          :auto-upload="false"
          :on-change="handleChange"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :multiple="false"
          accept=".pdf"
          :disabled="!versionNumber || !!uploadedFile"
          ref="uploadRef"
        >
          <div
            class="upload-area"
            :class="{ 'is-disabled': !versionNumber || !!uploadedFile }"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="upload-text">
              {{ uploadedFile ? '请先删除已有文件' : '点击上传' }}
            </div>
            <div class="el-upload__tip">只能上传 PDF 文件，且不超过 20MB</div>
          </div>
        </el-upload>
      </div>

      <!-- 已上传文件展示区域 -->
      <div v-if="uploadedFile" class="file-display">
        <div class="file-item">
          <el-icon><document /></el-icon>
          <span class="filename" @click="previewFile">
            {{ uploadedFile.name }}
          </span>
          <el-button type="danger" link @click="handleDelete">删除</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="提示"
      width="500"
      :before-close="handleClose"
    >
      <span>确定要删除该文件吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeleteConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PrivacyPolicy">
import { ref, onMounted } from 'vue';
import { uploadPic } from '@/api/Upload/upload';
import { ElMessage } from 'element-plus';
import { setFileModify, privacyPolicy } from '@/api/Set/set';

// 数据
const versionNumber = ref('');
const typeData = ref({});
const uploadedFile = ref(null);
const loading = ref(false);
const uploadRef = ref(null);
const dialogVisible = ref(false);
// 处理文件变更
const handleChange = async (file) => {
  if (!versionNumber.value) {
    ElMessage.warning('请先输入文本版本号');
    return;
  }

  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('picture', file.raw);

    const res = await uploadPic(formData);
    if (res.data.code === 200) {
      uploadedFile.value = {
        name: `${file.name.split('.')[0]}_${versionNumber.value}.pdf`,
        url: res.data.data.url,
      };
      ElMessage.success('文件上传成功');
      modifyFile();
    } else {
      ElMessage.error(res.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('文件上传失败');
  } finally {
    loading.value = false;
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  }
};

// 修改文件
const modifyFile = async () => {
  const res = await setFileModify({
    id: typeData.value.id,
    textType: '3',
    textKey: '隐私协议',
    textVersion: versionNumber.value,
    textValue: uploadedFile.value.url,
  });
  if (res.data.code === 200) {
    ElMessage.success('文件修改成功');
  } else {
    ElMessage.error(res.data.msg || '文件修改失败');
  }
};

// 根据类型获取ID
const getTypeId = async () => {
  try {
    const res = await privacyPolicy({
      textType: '3',
    });
    if (res.data.code === 200) {
      typeData.value = res.data.data || {}; // 确保有默认值
      // 如果有已上传的文件且数据不为空，进行回显
      if (typeData.value && typeData.value.textValue) {
        uploadedFile.value = {
          name: `隐私政策_${typeData.value.textVersion}.pdf`,
          url: typeData.value.textValue,
        };
        versionNumber.value = typeData.value.textVersion;
      } else {
        // 如果没有数据，重置所有相关状态
        uploadedFile.value = null;
        versionNumber.value = '';
      }
    } else {
      ElMessage.error(res.data.msg || '获取类型失败');
    }
  } catch (error) {
    console.error('获取类型数据失败:', error);
    ElMessage.error('获取类型数据失败');
    // 发生错误时重置状态
    typeData.value = {};
    uploadedFile.value = null;
    versionNumber.value = '';
  }
};

// 预览文件
const previewFile = () => {
  if (uploadedFile.value?.url) {
    window.open(uploadedFile.value.url, '_blank');
  }
};

// 删除文件
const handleDelete = () => {
  dialogVisible.value = true;
};
const handleDeleteConfirm = async () => {
  try {
    const res = await setFileModify({
      id: typeData.value.id,
      textType: '3',
      textKey: '隐私协议',
      textVersion: '',
      textValue: '',
    });

    if (res.data.code === 200) {
      uploadedFile.value = null;
      versionNumber.value = '';
      ElMessage.success('文件已删除');
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除操作失败');
    }
  }
  dialogVisible.value = false;
};
const handleClose = () => {
  dialogVisible.value = false;
};
// 上传前验证
const beforeUpload = (file) => {
  if (!versionNumber.value) {
    ElMessage.warning('请先输入文本版本号');
    return false;
  }

  const isPDF = file.type === 'application/pdf';
  const isLt20M = file.size / 1024 / 1024 < 20;

  if (!isPDF) {
    ElMessage.error('只能上传 PDF 文件！');
    return false;
  }
  if (!isLt20M) {
    ElMessage.error('文件大小不能超过 20MB！');
    return false;
  }

  return true;
};

// 页面加载时获取最后上传的文件
onMounted(() => {
  getTypeId();
});
</script>

<style lang="scss" scoped>
.privacy-container {
  padding: 20px;
  height: 610px;

  .input-section {
    margin-bottom: 20px;
    max-width: 500px;
    display: flex;
    align-items: center;

    .label {
      white-space: nowrap;
      margin-right: 10px;
      font-size: 14px;
      color: #606266;
    }
  }

  .upload-section {
    margin-bottom: 20px;
    max-width: 400px;

    .upload-box {
      :deep(.el-upload) {
        width: 100%;
        text-align: left;
      }

      .upload-area {
        width: 100%;
        padding: 30px 20px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;
        text-align: center;

        &:hover {
          border-color: #409eff;
        }

        &.is-disabled {
          cursor: not-allowed;
          background-color: #f5f7fa;
          border-color: #e4e7ed;

          &:hover {
            border-color: #e4e7ed;
          }

          .el-icon--upload,
          .upload-text,
          .el-upload__tip {
            color: #c0c4cc;
          }
        }

        .el-icon--upload {
          font-size: 28px;
          color: #8c939d;
          margin-bottom: 8px;
        }

        .upload-text {
          color: #606266;
          font-size: 14px;
          margin-bottom: 8px;
        }

        .el-upload__tip {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }

  .file-display {
    margin-top: 20px;

    .file-item {
      display: flex;
      align-items: center;
      padding: 10px;
      background: #f5f7fa;
      border-radius: 4px;
      max-width: 380px;

      .el-icon {
        margin-right: 8px;
        font-size: 20px;
        color: #909399;
      }

      .filename {
        flex: 1;
        color: #409eff;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style>
